﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;

namespace LanhuFx.Identity
{
    public class TokenService
    {
        public TokenService(
            Identity_DESHelper arg_desHelper,
            IHttpContextAccessor arg_accessor
            )
        {
            this._desHelper = arg_desHelper;
            this._accessor = arg_accessor;
        }

        private readonly Identity_DESHelper _desHelper;
        private readonly IHttpContextAccessor _accessor;

        public string Authorization
        {
            get
            {
                try
                {
                    if (_accessor == null)
                        return null;

                    return _accessor.HttpContext.Request.Headers["Authorization"].ToString();
                }
                catch
                {
                    return string.Empty;
                }

            }
        }

        public string AppCode
        {
            get
            {
                try
                {
                    if (_accessor == null)
                        return null;

                    return _accessor.HttpContext.Request.Headers["AppCode"].ToString();
                }
                catch
                {
                    return string.Empty;
                }

            }
        }

        public UserToken GetToken()
        {
            try
            {
                string arg_Authorization = Authorization;

                if (!string.IsNullOrEmpty(arg_Authorization))
{
                    return JsonConvert.DeserializeObject<UserToken>(_desHelper.Decrypt(arg_Authorization));
                }

                string arg_appCode = AppCode;

                if (!string.IsNullOrEmpty(arg_appCode))
                {
                    return new UserToken()
                    {
                        TeamId = Guid.Parse(arg_appCode)
                    };
                }

                return null;
            }
            catch
            {
                return null;
            }
        }
    }
}
